package spitfire.ksim.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JPanel;

import spitfire.ksim.algorithm.FuzzyRule;


/**
 * @author Adam
 *
 */
public class KFuzzyRulePanel extends JPanel{

	private static final long serialVersionUID = 6529392651431752957L;
	
	public int WIDTH = 300;
	public int HEIGHT = 100;
	private FuzzyRule rule;
	private double windowMinValue;
	private double windowMaxValue;

	public KFuzzyRulePanel() {
		setPreferredSize(new Dimension(WIDTH, HEIGHT));
		
		addMouseWheelListener(new MouseWheelListener() {
			@Override
			public void mouseWheelMoved(MouseWheelEvent e) {
				double scale = e.getWheelRotation() > 0 ? 1.1 : 0.9;
				double ratio = (windowMaxValue*scale) / (windowMinValue/scale);
				if (ratio > 1.1 && ratio < 500) {
					windowMaxValue *= scale;
					windowMinValue /= scale;
				}
//				System.out.println(scale + " " + windowMinValue + "/" + windowMaxValue);
				repaint();
			}
		});
	}
	
	public void setFuzzyRule(FuzzyRule rule) {
		this.rule = rule;
		windowMaxValue = rule.getrMax() * 1.3;
		windowMinValue = rule.getrMin() / 1.3;
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (rule != null) {
			setBackground(Color.WHITE);
//			if (ruleCopy != subEntry.rule) {
//				oldRule = ruleCopy;
//				ruleCopy = subEntry.rule;
//			}
			g.setColor(Color.RED);
			drawRule(g, rule);
		} else {
			setBackground(Color.GRAY);
		}
//		if (oldRule != null) {
//			g.setColor(Color.BLUE);
//			drawRule(g, oldRule);
//		}
	}
	
	/**
	 * Draw the sketch of the rule with the given graphics object
	 * 
	 * @param g
	 * @param rule
	 */
	private void drawRule(Graphics g, FuzzyRule rule) {
		Double[] X = new Double[rule.getxList().size()];
		Double[] Y = new Double[rule.getyList().size()];
		X = rule.getxList().toArray(X);
		Y = rule.getyList().toArray(Y);
		if (X.length != Y.length) {
			throw new RuntimeException();
		}
		double[] uniX = new double[X.length];
		double windowSize = (windowMaxValue - windowMinValue);
		for (int i = 0; i < X.length; i++) {
			uniX[i] = (X[i] - windowMinValue) / windowSize;
//			if ((X[i] - windowMinValue)<0) {
//			System.out.println("side: " + (X[i] - windowMinValue));
//			}
		}
		int width = getWidth();
		int height = getHeight();
//		System.out.println("width: " + height);
		for (int i = 0; i < Y.length; i++) {
			g.drawOval((int)(uniX[i] * width), (int)((1 - Y[i]) * height), 2, 2);
			if (i != 0) {
				g.drawLine((int)(uniX[i] * width), (int)((1 - Y[i]) * height),
						(int)(uniX[i - 1] * width), (int)((1 - Y[i - 1]) * height));
			}
		}
	}
}
